package hot150;

import java.util.HashMap;

// https://leetcode.cn/problems/roman-to-integer/description/?envType=study-plan-v2&envId=top-interview-150
public class q17 {

    HashMap<Character, Integer> map = new HashMap<>() {{
        put('I', 1);
        put('V', 5);
        put('X', 10);
        put('L', 50);
        put('C', 100);
        put('D', 500);
        put('M', 1000);
    }};

    public int romanToInt(String s) {
        return method1(s);
    }


    /**
     * 模拟
     * 5 ms
     * 复杂度O(n)
     */
    public int method1(String s) {
        char[] chr = s.toCharArray();
        int sum = 0;
        int n = chr.length;
        for (int i = 0; i < n; i++) {
            char c = chr[i];
            // 前面小于后面则减法，否则加法
            if (i < n - 1 && map.get(c) < map.get(chr[i + 1])) {
                sum -= map.get(c);
            }
            else {
                sum += map.get(c);
            }
        }
        return sum;
    }
}
